#target illustrator
(function () {
    if (app.documents.length === 0) { alert("先打开文档"); return; }
    var doc = app.activeDocument;
    if (!doc.selection || doc.selection.length === 0) { alert("请先选择路径"); return; }

    // 选择：1=左对齐；2=右对齐
    var ans = prompt("选择对齐端：\n1) 左端点左对齐\n2) 右端点右对齐", "1");
    if (ans === null) return;
    if (ans !== "1" && ans !== "2") { alert("请输入 1 或 2"); return; }
    var alignRight = (ans === "2");

    var EPS = 0.001;
    function abs(x){ return x<0?-x:x; }

    // 找“水平段”：优先 |dy| 最小；若接近则取 |dx| 最大
    function analyze(p) {
        if (p.closed) return null;
        var n = p.pathPoints.length;
        if (n !== 2 && n !== 3) return null;

        var pts = [], i;
        for (i = 0; i < n; i++) {
            var a = p.pathPoints[i].anchor;
            pts[i] = [a[0], a[1]];
        }

        var bi = 0, bj = 1;
        var bestDY = abs(pts[0][1] - pts[1][1]);
        var bestDX = abs(pts[0][0] - pts[1][0]);
        if (n === 3) {
            var pair = [[0,1],[0,2],[1,2]];
            for (var t = 0; t < 3; t++) {
                var a = pair[t][0], b = pair[t][1];
                var dy = abs(pts[a][1] - pts[b][1]);
                var dx = abs(pts[a][0] - pts[b][0]);
                if (dy + 1e-9 < bestDY || (abs(dy - bestDY) <= EPS && dx > bestDX)) {
                    bestDY = dy; bestDX = dx; bi = a; bj = b;
                }
            }
        }

        var leftIdx  = (pts[bi][0] <= pts[bj][0]) ? bi : bj;
        var rightIdx = (leftIdx === bi) ? bj : bi;

        // 右侧是否有竖直点（x 与右端相同且 y 不同）
        var hasVert = false, vertIdx = -1;
        if (n === 3) {
            for (i = 0; i < 3; i++) {
                if (i === leftIdx || i === rightIdx) continue;
                if (abs(pts[i][0] - pts[rightIdx][0]) <= EPS &&
                    abs(pts[i][1] - pts[rightIdx][1]) > EPS) {
                    hasVert = true; vertIdx = i; break;
                }
            }
        }

        return {
            path: p,
            pts: pts,
            n: n,
            leftIdx: leftIdx,
            rightIdx: rightIdx,
            leftX: pts[leftIdx][0],
            leftY: pts[leftIdx][1],
            rightX: pts[rightIdx][0],
            rightY: pts[rightIdx][1],
            hasVert: hasVert,
            vertIdx: vertIdx
        };
    }

    // 收集
    var infos = [], i;
    for (i = 0; i < doc.selection.length; i++) {
        var it = doc.selection[i];
        if (it.typename === "PathItem") {
            var inf = analyze(it);
            if (inf) infos.push(inf);
        }
    }
    if (infos.length === 0) { alert("未找到可用的 2/3 端点开放线段"); return; }

    // 1) 水平对齐（左对齐或右对齐）
    if (!alignRight) {
        // 左对齐：所有水平段“左端点 x”设为最小
        var minLeftX = infos[0].leftX;
        for (i = 1; i < infos.length; i++) if (infos[i].leftX < minLeftX) minLeftX = infos[i].leftX;

        for (i = 0; i < infos.length; i++) {
            var infoL = infos[i], pL = infoL.path, kL;
            var ptsL = [];
            for (kL = 0; kL < infoL.pts.length; kL++) ptsL[kL] = [infoL.pts[kL][0], infoL.pts[kL][1]];
            ptsL[infoL.leftIdx][0] = minLeftX; // 只动左端点 x
            pL.setEntirePath(ptsL);
            for (kL = 0; kL < pL.pathPoints.length; kL++) {
                var ptL = pL.pathPoints[kL];
                ptL.leftDirection = ptL.rightDirection = ptL.anchor;
                ptL.pointType = PointType.CORNER;
            }
            // 同步
            infoL.pts = ptsL;
            infoL.leftX = minLeftX;
            infoL.leftY = ptsL[infoL.leftIdx][1];
        }
    } else {
        // 右对齐：所有水平段“右端点 x”设为最大；若有右侧竖直点，同步它的 x
        var maxRightX = infos[0].rightX;
        for (i = 1; i < infos.length; i++) if (infos[i].rightX > maxRightX) maxRightX = infos[i].rightX;

        for (i = 0; i < infos.length; i++) {
            var infoR = infos[i], pR = infoR.path, kR;
            var ptsR = [];
            for (kR = 0; kR < infoR.pts.length; kR++) ptsR[kR] = [infoR.pts[kR][0], infoR.pts[kR][1]];
            ptsR[infoR.rightIdx][0] = maxRightX;           // 右端点 x 对齐
            if (infoR.hasVert && infoR.vertIdx >= 0) {     // 保持右侧竖直段
                ptsR[infoR.vertIdx][0] = maxRightX;
            }
            pR.setEntirePath(ptsR);
            for (kR = 0; kR < pR.pathPoints.length; kR++) {
                var ptR = pR.pathPoints[kR];
                ptR.leftDirection = ptR.rightDirection = ptR.anchor;
                ptR.pointType = PointType.CORNER;
            }
            // 同步
            infoR.pts = ptsR;
            infoR.rightX = maxRightX;
            infoR.rightY = ptsR[infoR.rightIdx][1];
        }
    }

    // 2) 垂直方向等距（按所选端点的 y 作为基准）
    var nItems = infos.length, order = [], baseY = [];
    for (i = 0; i < nItems; i++) {
        baseY[i] = alignRight ? infos[i].pts[infos[i].rightIdx][1]
                              : infos[i].pts[infos[i].leftIdx][1];
        order[i] = i;
    }
    order.sort(function (a, b) { return baseY[a] - baseY[b]; });

    var yMin = baseY[order[0]];
    var yMax = baseY[order[nItems - 1]];
    var span = yMax - yMin;
    var stepY = (nItems > 1) ? (span / (nItems - 1)) : 0;

    for (var j = 0; j < nItems; j++) {
        var id = order[j];
        var info2 = infos[id], path = info2.path, m;

        var curY = alignRight ? info2.pts[info2.rightIdx][1]
                              : info2.pts[info2.leftIdx][1];
        var targetY = yMin + stepY * j;
        var dy = targetY - curY;

        // 右端点“当前坐标”（供两点路径补竖直点）
        var rightOld = [info2.pts[info2.rightIdx][0], info2.pts[info2.rightIdx][1]];

        var out;

        if (info2.n === 2) {
            // —— 关键修复：两点路径按坐标重建点序 —— //
            var leftNew  = [ info2.pts[info2.leftIdx][0],  info2.pts[info2.leftIdx][1]  + dy ];
            var rightNew = [ info2.pts[info2.rightIdx][0], info2.pts[info2.rightIdx][1] + dy ];
            // 强制输出 [leftNew, rightNew, rightOld]，确保竖直段接在“右端”
            out = [ leftNew, rightNew, rightOld ];
        } else {
            // 三点路径：仅改水平段两端点的 y，竖直点不动（保持原点序即可）
            out = [];
            for (m = 0; m < info2.pts.length; m++) out[m] = [info2.pts[m][0], info2.pts[m][1]];
            out[info2.leftIdx][1]  = out[info2.leftIdx][1]  + dy;
            out[info2.rightIdx][1] = out[info2.rightIdx][1] + dy;
        }

        path.setEntirePath(out);

        for (m = 0; m < path.pathPoints.length; m++) {
            var ptt = path.pathPoints[m];
            ptt.leftDirection = ptt.rightDirection = ptt.anchor;
            ptt.pointType = PointType.CORNER;
        }
    }
})();
